package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.service.impl.DishServiceImpl;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/admin/dish")
@Api(tags = "菜品管理")
public class DishController {

  @Autowired
  private DishService dishService;
  @Autowired
  private RedisTemplate redisTemplate;

  @ApiOperation("新增菜品")
  @PostMapping
  public Result save(@RequestBody DishDTO dishDTO){
    log.info("新增菜品dishDTO:{}",dishDTO);
    dishService.saveWithFlavor(dishDTO);
    // 精确清理redis缓存
    String key = "dish_" + dishDTO.getCategoryId();
    //redisTemplate.delete(key);
    clearRedisCache(key);
    return Result.success();
  }

  /**
   * 菜品分页查询
   * @return
   */
  @GetMapping("/page")
  @ApiOperation("菜品分页查询")
  public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO){
    PageResult pageResult = dishService.page(dishPageQueryDTO);
    return Result.success(pageResult);
  }

  /**
   * 批量删除菜品
   * @param ids
   * @return
   */
  @DeleteMapping
  @ApiOperation("批量删除菜品")
  public Result delete(@RequestParam List<Long> ids){ // 加上@RequestParam可以把1，2，3这样的字符串封装到List集合中
    log.info("删除菜品ids:{}",ids);
    dishService.deleteBatch(ids);
    // 批量删除时，不用查出所有的菜品，直接删除所有的dish_开头的redis缓存
    //Set keys = redisTemplate.keys("dish_*");
    //redisTemplate.delete(keys);
    clearRedisCache("dish_*");
    return Result.success();
  }

  /**
   * 根据id查询菜品详情
   * @param id
   * @return
   */
  @GetMapping("/{id}")
  @ApiOperation("根据id查询菜品详情")
  public Result<DishVO> getDishById(@PathVariable Long id){
    DishVO dishVO = dishService.getById(id);
    return Result.success(dishVO);
  }

  @PutMapping
  @ApiOperation("修改菜品")
  public Result updateDish(@RequestBody DishDTO dishDTO){
    dishService.updateWithFlavor(dishDTO);
    // 修改时，由于可以修改菜品的分类，要查出两份缓存数据，所以直接把redis的dish缓存全部清理掉
    //Set keys = redisTemplate.keys("dish_*");
    //redisTemplate.delete(keys);
    clearRedisCache("dish_*");
    return Result.success();
  }
  /**
   * 根据分类id查询菜品
   *
   * @param categoryId
   * @return
   */
  @GetMapping("/list")
  @ApiOperation("根据分类id查询菜品")
  public Result<List<Dish>> list(Long categoryId) {
    List<Dish> list = dishService.list(categoryId);
    return Result.success(list);
  }

  private void clearRedisCache(String pattern){
    Set keys = redisTemplate.keys(pattern);
    redisTemplate.delete(keys);
  }
}
